import React, { useState, useEffect, useRef } from 'react';
import { Tabs, Card, Space, Radio, Select, Button, Drawer, message } from 'antd';
import { connect, FormattedMessage } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import MonacoEditor from 'react-monaco-editor';
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution';
import { CaretLeftOutlined, SaveOutlined } from '@ant-design/icons';
import DataDesign from './components/DataDesign';
import ReportEdit from './components/ReportEdit';
import ReportList from './components/ReportList';
import request from '@/utils/request';
import ProTable from '@ant-design/pro-table';
import ActiveReport from './components/ActiveReport';

const { TabPane } = Tabs;
const apiURL = '/api/services/app/ERPReports/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [defTab, setDefTab] = useState('1');
  const [code, setCode] = useState('// type your code...');
  const [theme, setTheme] = useState('vs-dark');
  const [fontSize, setFontSize] = useState(16);
  const [record, setRecord] = useState<any>(null);
  const [dataAct, setDataAct] = useState('');
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [visible3, setVisible3] = useState(false);
  const [dyColumns, setDyColumns] = useState([]);
  const ReportListRef = useRef<any>();

  useEffect(() => {
    // componentDidMount
  }, []);

  const editorDidMount = (editor: any) => {
    console.log('editorDidMount', editor);
    editor.focus();
  };

  const onChange = (newValue: any) => {
    setCode(newValue);
  };

  const themeChange = (e: any) => {
    setTheme(e.target.value);
  };

  const fontsizeChange = (fontSize: any) => {
    setFontSize(fontSize);
  };

  const setCurrent = (record: any) => {
    request(apiURL + 'GetReportObj', {
      method: 'GET',
      params: { id: record.id },
    }).then((response) => {
      if (response) {
        if (response.success) {
          try {
            const result = response.result;
            setRecord(result);
            setCode(result.sqlDefine);
            setDefTab('2');
            setDataAct('Update');
            setDataSource([]);
            setDyColumns(result.filedList);
          } catch {}
        }
      }
    });
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const doSave = () => {
    if (!record) return;
    record.sqlDefine = code;
    if (Array.isArray(record.authUsers)) {
      record.authUsers = record.authUsers.join(',');
    }
    request(apiURL + 'Update', {
      method: 'PUT',
      data: record,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success('保存成功！');
        }
        setLoading(false);
      }
    });
  };

  const runSQL = async (params: any = null) => {
    if (!record) {
      return [];
    }
    const result: any = {
      data: [],
      total: 0,
    };
    await request(apiURL + 'RunSQL', {
      method: 'POST',
      data: { id: record.id, args: params },
    }).then((response) => {
      if (response) {
        if (response.success) {
          result.data = response.result;
          result.total = response.totalCount;
        }
        setLoading(false);
      }
    });
    return result;
  };

  const openDataDesign = (visible: boolean) => {
    if (record?.fielDefine) {
      setVisible(visible);
    }
  };

  const openActiveReport = (visible: boolean) => {
    setVisible3(visible);
  };

  const options = {
    selectOnLineNumbers: true,
    fontSize,
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
          <TabPane tab={<FormattedMessage id="pages.allReport" />} key="1">
            <ReportList ref={ReportListRef} setCurrent={(e: any) => setCurrent(e)} />
          </TabPane>
          <TabPane tab={<FormattedMessage id="pages.report.design" />} key="2">
            <Tabs defaultActiveKey="S1" tabPosition={'left'}>
              <TabPane tab={<FormattedMessage id="pages.design" />} key="S1">
                <Card
                  title={record ? record.reportName : <FormattedMessage id="pages.dataModel" />}
                  bordered={false}
                  extra={[
                    <Space key="S1">
                      <FormattedMessage id="pages.codeStyle" />：
                      <Radio.Group value={theme} onChange={(v) => themeChange(v)}>
                        <Radio.Button key="vs" value="vs">
                          <FormattedMessage id="pages.Light" />
                        </Radio.Button>
                        <Radio.Button key="vs-dark" value="vs-dark">
                          <FormattedMessage id="pages.Dark" />
                        </Radio.Button>
                        <Radio.Button key="hc-black" value="hc-black">
                          <FormattedMessage id="pages.Highlight" />
                        </Radio.Button>
                      </Radio.Group>
                      <FormattedMessage id="pages.fontSize" />：
                      <Select value={fontSize} onChange={(v) => fontsizeChange(v)}>
                        <Select.Option key={12} value={12}>
                          12
                        </Select.Option>
                        <Select.Option key={14} value={14}>
                          14
                        </Select.Option>
                        <Select.Option key={16} value={16}>
                          16
                        </Select.Option>
                        <Select.Option key={18} value={18}>
                          18
                        </Select.Option>
                        <Select.Option key={20} value={20}>
                          20
                        </Select.Option>
                      </Select>
                      <Button
                        type="primary"
                        icon={<SaveOutlined />}
                        onClick={doSave}
                        disabled={record == null}
                      >
                        <span>
                          <FormattedMessage id="pages.save" />
                        </span>
                      </Button>
                      <Button
                        type="ghost"
                        disabled={record == null}
                        onClick={() => {
                          setVisible2(true);
                          setDataAct('Update');
                        }}
                      >
                        <FormattedMessage id="pages.reportAttribute" />
                      </Button>
                      <Button
                        type="ghost"
                        disabled={record == null || record.classID == 'procedure'}
                        onClick={() => openDataDesign(true)}
                      >
                        <FormattedMessage id="pages.dataModel" />
                      </Button>
                      <Button
                        type="ghost"
                        disabled={record == null || record.classID == 'procedure'}
                        onClick={() => openActiveReport(true)}
                      >
                        <FormattedMessage id="pages.report.design" />
                      </Button>
                      <Button
                        type="primary"
                        danger
                        disabled={record == null}
                        icon={<CaretLeftOutlined />}
                        onClick={() => runSQL()}
                        hidden
                      >
                        <FormattedMessage id="pages.run" />
                      </Button>
                    </Space>,
                  ]}
                >
                  <MonacoEditor
                    width="100%"
                    height="500"
                    language="sql"
                    theme={theme}
                    value={code}
                    options={options}
                    onChange={onChange}
                    editorDidMount={editorDidMount}
                  />
                </Card>
              </TabPane>
              <TabPane
                tab={<FormattedMessage id="pages.run" />}
                key="S2"
                disabled={record && record.classID == 'procedure'}
              >
                <ProTable
                  columns={dyColumns}
                  rowKey={record?.rowKey}
                  bordered={record?.bordered}
                  toolBarRender={false}
                  scroll={{
                    y: record?.reportHeight ? record?.reportHeight : 300,
                  }}
                  request={async (params = {}) => {
                    return runSQL(params);
                  }}
                  search={{
                    filterType: 'query',
                  }}
                />
              </TabPane>
            </Tabs>
          </TabPane>
        </Tabs>
      </Card>
      <Drawer
        title={record ? record.reportName : <FormattedMessage id="pages.dataModel" />}
        placement="right"
        closable={true}
        visible={visible}
        onClose={() => setVisible(false)}
        mask={true}
        maskClosable={true}
        destroyOnClose
        width={960}
      >
        <DataDesign data={record} />
      </Drawer>
      <Drawer
        title={<FormattedMessage id="pages.reportAttribute" />}
        placement="right"
        closable={true}
        visible={visible2}
        onClose={() => setVisible2(false)}
        mask={true}
        maskClosable={true}
        destroyOnClose
        width={960}
      >
        <ReportEdit
          data={record}
          act={dataAct}
          callback={(resp: any) => {
            setRecord(resp);
            console.log(ReportListRef);
            // ReportListRef.current.fetchDatas();
          }}
        />
      </Drawer>
      <Drawer
        title={<FormattedMessage id="pages.report.design" />}
        placement="right"
        closable={true}
        visible={visible3}
        onClose={() => setVisible3(false)}
        mask={true}
        maskClosable={true}
        destroyOnClose
        width={1280}
      >
        <ActiveReport />
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
